package com.bootcamp.mall.controller.admin;

/**
 * @program: mall
 * @author: Keyu Li
 * @create: 2021-11-10 14:47
 **/

import com.bootcamp.mall.model.GoodsType;
import com.bootcamp.mall.model.Result;
import com.bootcamp.mall.model.Spec;
import com.bootcamp.mall.model.bo.goods.GoodsBO;
import com.bootcamp.mall.model.bo.goods.MsgBO;
import com.bootcamp.mall.model.vo.goods.MsgVO;
import com.bootcamp.mall.model.vo.goods.GetGoodsInfoVO;
import com.bootcamp.mall.model.vo.goods.GoodsVO;
import com.bootcamp.mall.service.goods.GoodsService;
import com.bootcamp.mall.service.goods.GoodsServiceImpl;
import com.bootcamp.mall.utils.FileUploadUtil;
import com.bootcamp.mall.utils.JSONUtil;
import com.bootcamp.mall.utils.StringUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "GoodsServlet", value = "/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {

    Gson gson = new Gson();
    GoodsService goodsService = new GoodsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/admin/goods/", "");
        if ("getType".equals(op)) {
            opGetTypes(request, response);
        } else if ("getGoodsByType".equals(op)) {
            opGetGoodsByType(request, response);
        } else if ("deleteType".equals(op)) {
            opDeleteType(request, response);
        } else if ("getGoodsInfo".equals(op)) {
            opGetGoodsInfo(request, response);
        } else if ("deleteGoods".equals(op)) {
            opDeleteGoods(request, response);
        } else if ("noReplyMsg".equals(op)) {
            opNoReplyMsg(request, response);
        } else if ("repliedMsg".equals(op)) {
            opRepliedMsg(request, response);
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/admin/goods/", "");
        if ("addType".equals(op)) {
            opAddTypes(request, response);
        } else if ("imgUpload".equals(op)) {
            opImgUpload(request, response);
        } else if ("addGoods".equals(op)) {
            opAddGoods(request, response);
        } else if ("addSpec".equals(op)) {
            opAddSpec(request, response);
        } else if ("deleteSpec".equals(op)) {
            opDeleteSpec(request, response);
        } else if ("updateGoods".equals(op)) {
            opUpdateGoods(request, response);
        } else if ("reply".equals(op)) {
            opReply(request, response);
        }
    }


    private void opReply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // json转换为对象四连
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            MsgBO msgBO = gson.fromJson(asJsonObject, MsgBO.class);
            Integer code = goodsService.replyMsg(msgBO);
            if (code == -1) {
                writer.println(gson.toJson(Result.error("回复内容不能为空！")));
                return;
            } else if (code == 0) {
                writer.println(gson.toJson(Result.ok()));
                return;
            }
            writer.println(gson.toJson(Result.error("服务器异常！")));
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("前端参数异常！")));
        }
    }

    private void opRepliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<MsgVO> msgBOS = goodsService.showMsg(0);
        // 没有也是ok
        response.getWriter().println(gson.toJson(Result.ok(msgBOS)));
    }

    private void opNoReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        List<MsgVO> msgBOS = goodsService.showMsg(1);
        // 没有也是ok
        response.getWriter().println(gson.toJson(Result.ok(msgBOS)));
    }


    private void opUpdateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            GoodsBO updateGoodsBO = gson.fromJson(asJsonObject, GoodsBO.class);
            Integer code = goodsService.updateGoods(updateGoodsBO);
            if (code == -1) {
                writer.println(gson.toJson(Result.error("添加规格参数异常,请确保数字项不能为负！")));
            } else if (code == 1) {
                writer.println(gson.toJson(Result.error("规格不能同名！")));
            } else if (code == 500) {
                writer.println(gson.toJson(Result.error("服务器未知异常错误！")));
            } else
                writer.println(gson.toJson(Result.ok()));
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("添加规格参数异常,请确保数字项填写正确！")));
        }
    }

    private void opDeleteSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取解析json字符串
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // json转换为字符串
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            Spec deleteSpec = gson.fromJson(asJsonObject, Spec.class);
            goodsService.deleteSpec(deleteSpec);
            writer.println(gson.toJson(Result.ok()));
        } catch (Exception e) {
            // 如果参数非法，则一定会参数转换异常
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("删除规格参数异常！")));
        }
    }

    private void opAddSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取解析json字符串
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            Spec addSpec = gson.fromJson(asJsonObject, Spec.class);
            writer.println(gson.toJson(Result.ok(addSpec)));
        } catch (Exception e) {
            // 如果参数非法，则一定会参数转换异常
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("添加规格参数异常,请确保数字项填写正确！")));
        }

    }


    private void opDeleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 通过parameter获取id
        int id;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        }catch (NumberFormatException e){
            writer.println(gson.toJson(Result.error("前端参数异常！")));
            return;
        }
        boolean status = goodsService.deleteGoods(id);
        if (status) {
            // 正常操作
            writer.println(gson.toJson(Result.ok()));
            return;
        }
        // 发生异常
        writer.println(gson.toJson(Result.error("服务器异常")));
    }


    private void opGetGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 通过url获取id
        int id;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        }catch (NumberFormatException e){
            writer.println(gson.toJson(Result.error("前端参数异常！")));
            return;
        }
        // service查询，获取vo
        GetGoodsInfoVO getGoodsInfoVO = goodsService.getGoodsInfo(id);
        // 返回vo,不会报错
        writer.println(gson.toJson(Result.ok(getGoodsInfoVO)));
    }

    private void opAddGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 接收json
        String jsonContent = JSONUtil.parseContent(request);
        // 例行判断是否为空
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(Result.error("前端错误！"));
            return;
        }
        // json转换为AddGoodsBO对象,捕获异常,以免非法参数
        GoodsBO addGoodsBO = null;
        try {
            JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
            addGoodsBO = gson.fromJson(asJsonObject, GoodsBO.class);
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("规格参数错误，只能为数字！")));
            return;
        }
        Integer code = goodsService.addGoods(addGoodsBO);
        if (code == -1) {
            writer.println(gson.toJson(Result.error("规格参数错误，不能为负数！")));
            return;
        } else if (code == 0) {
            // 正常返回
            writer.println(gson.toJson(Result.ok()));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));
    }


    private void opDeleteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取id参数
        Integer typeId = null;
        try {
            // 如果参数为 null，或非法，会有 NumberFormatException
            typeId = Integer.parseInt(request.getParameter("typeId"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数非法！")));
            return;
        }
        if (typeId == 1) {
            writer.println(gson.toJson(Result.error("当前类目为默认类目,禁止删除！")));
            return;
        }
        // 删除typeId,返回int
        Integer code = goodsService.deleteType(typeId);
        if (code == 0) {
            writer.println(gson.toJson(Result.ok()));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));

    }


    private void opImgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 利用工具类存储图片
        String imgPath = FileUploadUtil.multiFormToMap(request);
        if (imgPath == null) {
            writer.println(gson.toJson(Result.error("图片存储失败！")));
            return;
        }
        writer.println(gson.toJson(Result.ok(imgPath)));
    }

    private void opAddTypes(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        String jsonContent = JSONUtil.parseContent(request);
        // 如果为空，说明前端错误
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端请求参数错误！")));
            return;
        }
        // 转化为type对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        GoodsType goodsType = gson.fromJson(asJsonObject, GoodsType.class);
        boolean status = goodsService.addTypes(goodsType);
        if (status) {
            writer.println(gson.toJson(Result.ok()));
            return;
        }
        writer.println(gson.toJson(Result.error("不能有重复的类目")));
    }

    private void opGetGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取typeId
        int typeId;
        try {
            typeId = Integer.parseInt(request.getParameter("typeId"));
        }catch (NumberFormatException e){
            writer.println(gson.toJson(Result.error("前端参数异常！")));
            return;
        }
        List<GoodsVO> goodsByTypeVOS = goodsService.getGoodsByType(typeId);
        writer.println(gson.toJson(Result.ok(goodsByTypeVOS)));
    }

    private void opGetTypes(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<GoodsType> goodsByTypeVOs = goodsService.getTypes();
        // 即便没有数据，也会返回空
        response.getWriter().println(gson.toJson(Result.ok(goodsByTypeVOs)));
    }

}
